package com.ruoyi.system.timing.entity;

import com.ruoyi.system.timing.callback.TimingCallback;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : anxinr
 * @date : 2023/8/16 16:00
 */
@Slf4j
@ToString
@Getter
@Setter
public class PoolDomain {

    public static final SimpleDateFormat HH_MM = new SimpleDateFormat("HH:mm");

    private final LinkedList<String> timeRecordList = new LinkedList<>() ;

    private Boolean waiting = Boolean.FALSE ;

    private Long id ;

    private final Object data ;

    private final String name ;

    private final String startTime ;

    private final String endTime ;

    private TimingCallback callback ;

    private Integer frequency ;

    private Integer status ;

    private Integer noticeCount ;

    private Integer noticeCountRecord = 0 ;

    public void setStatus(Integer status) {
        this.status = status ;
    }

    public Integer getStatus() {
        if (Objects.isNull(this.status)) {
            this.status = 0 ;
        }
        return this.status ;
    }

    /**
     * 当前任务是否符合触发频率
     * @return String
     */
    public boolean complianceFrequency() {
        String frequencyTime = this.getLastTime();
        String nowTime = HH_MM.format(new Date());
        boolean result = false ;
        if (StringUtils.isNotBlank(frequencyTime)) {
            if (nowTime.equals(frequencyTime)) {
                result = Boolean.TRUE;
                this.putTime(frequencyTime);
                log.info("当前任务 -> {} 符合触发频率" ,this.getName());
            } else {
                log.info("当前任务 -> {} 未符合触发频率,开始时间为 -> {} ,符合的下次触发时间为 -> {} ,当前时间为 -> {}" ,this.getName() ,this.getStartTime() ,frequencyTime ,nowTime);
            }
        }
        try {
            Date parseFrequencyTime = HH_MM.parse(frequencyTime);
            Date parseNowTime = HH_MM.parse(nowTime);
            if (parseNowTime.getTime() >= parseFrequencyTime.getTime()) {
                log.info("任务 -> {} 触发时间自动匹配补全时间机制" ,this.getName());
                mateCompletionFrequencyTiming(parseFrequencyTime ,parseNowTime) ;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result ;
    }

    private void mateCompletionFrequencyTiming(Date frequencyTime, Date nowTime) {
        Calendar instance = Calendar.getInstance();
        while (nowTime.getTime() >= frequencyTime.getTime()){
            instance.setTime(frequencyTime) ;
            instance.add(Calendar.MINUTE ,this.getFrequency()) ;
            frequencyTime = instance.getTime() ;
            String format = HH_MM.format(frequencyTime);
            this.putTime(format);
        }
    }

    /**
     * 存储触发时间
     * @param time
     */
    public void putTime(String time) {
        if (timeRecordList.contains(time)) {
            return;
        }
        timeRecordList.addLast(time) ;
    }

    /**
     * 获取最近一次触发的时间
     * @return 最近一次触发的时间
     */
    public String getLastTime() {
        String last = null ;
        try {
            last = timeRecordList.getLast();
        }catch (NoSuchElementException e){
            last = null ;
        }
        if (StringUtils.isBlank(last)) {
            last = startTime.substring(0 ,startTime.lastIndexOf(":") + 1) ;
            Date parse = null;
            try {
                parse = HH_MM.parse(last);
            } catch (Exception e) {
                last = startTime.substring(0 ,startTime.lastIndexOf(":") + 1) ;
                parse = null;
                try {
                    parse = HH_MM.parse(last);
                } catch (Exception e1) {
                    return null ;
                }
            }
            Calendar instance = Calendar.getInstance();
            instance.setTime(parse) ;
            instance.add(Calendar.MINUTE ,this.getFrequency());
            last = HH_MM.format(instance.getTime());
            this.putTime(last) ;
        }
        return last;
    }

    /**
     * 获取最近一次触发的时间
     * @return Date
     */
    public Date getLastDateTime() {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        String last = this.getLastTime();
        if (StringUtils.isNotBlank(last)) {
            try {
                return format.parse(last) ;
            } catch (ParseException e) {
                return null ;
            }
        }else {
            return null ;
        }

    }

    /**
     * 设置回调逻辑
     * @param callback
     */
    public void setCallback (TimingCallback callback) {
        this.callback = callback ;
    }

    /**
     * 调用回调方法
     */
    public void callback() {
        this.callback.callBack(this);
    }

    /**
     * 设置触发频率  （分钟）
     * @param frequency
     */
    public void setFrequency(Integer frequency) {
        this.frequency = frequency ;
    }

    /**
     * 构造器
     * @param data
     * @param name
     * @param startTime
     * @param endTime
     * @param frequency
     */
    public PoolDomain(Object data ,String name ,String startTime ,String endTime ,Integer status ,Integer frequency){
        this.data = data ;
        this.startTime = startTime ;
        this.endTime = endTime ;
        this.name = name ;
        this.status = status ;
        this.frequency = frequency ;
    }

    /**
     * 构造器
     * @param data
     * @param name
     * @param startTime
     * @param endTime
     * @param frequency
     * @param callback
     */
    public PoolDomain(Object data ,String name ,String startTime ,String endTime ,Integer status ,Integer frequency ,TimingCallback callback){
        this.data = data ;
        this.startTime = startTime ;
        this.endTime = endTime ;
        this.frequency = frequency ;
        this.name = name ;
        this.status = status ;
        this.callback = callback ;
    }
}
